package v1

import (
	"chat/global"
	"chat/internal/common/response"
	"chat/internal/service"
	"github.com/gin-gonic/gin"
	"net/http"
	"path"
	"strconv"
	"strings"
	"time"
)

func UploadAvatar(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		global.Logger.Errorf("获取文件失败: %v", err)
		c.JSON(http.StatusOK, response.FailMsg("获取文件失败"))
		return
	}
	idStr := c.PostForm("uid")
	uid, err := strconv.Atoi(idStr)
	if err != nil {
		global.Logger.Errorf("获取用户id失败: %v", err)
		c.JSON(http.StatusOK, response.FailMsg("获取用户id失败"))
		return
	}

	fileName := strconv.FormatInt(time.Now().Unix(), 10) + "-" + file.Filename
	filepath := path.Join("image", fileName)

	fileExt := strings.ToLower(path.Ext(file.Filename))
	if ok, _ := global.FileSet[fileExt]; !ok {
		c.JSON(http.StatusOK, response.FailMsg("图片类型不支持"))
		return
	}
	err = c.SaveUploadedFile(file, "./"+filepath)
	if err != nil {
		c.JSON(http.StatusOK, response.FailMsg("SaveUploadedFile err"))
		return
	}

	url := "http://" + c.Request.Host + "/image/" + fileName

	err = service.UpdateAvatarByUid(uid, url)
	if err != nil {
		c.JSON(http.StatusOK, response.FailMsg("UpdateAvatarByUid err"))
		return
	}

	c.JSON(http.StatusOK, response.SuccessMsg(gin.H{"url": url}))
}
